<template>
  <!--  设备调试页面-->
  <el-container class="content">
    <el-header class="heads">
      <div>
        <el-divider content-position="left"><span style="color:#228AF5">选择要操作的摄像机</span></el-divider>
        <el-select v-model="cameraId" style="width: 100%" allow-create filterable clearable placeholder="选择摄像机">
          <el-option
            v-for="item in cameraSelectList"
            :key="item.id"
            :label="item.name"
            :value="item.name">
          </el-option>
        </el-select>
        <el-button style="width: 100%;margin-top: 10px" type="danger" v-if="connectStatus" @click="connectEquip()">断开连接
        </el-button>
        <el-button type="primary" v-else style="background-color: green;color: white;width: 100%;margin-top: 10px"
                   @click="connectEquip()">连接设备
        </el-button>
      </div>
      <div v-if="connectStatus">
        <el-divider content-position="left"><span style="color:#228AF5">下发指令选择</span></el-divider>
        <el-select v-model="form.msg_type" style="width: 100%" filterable clearable placeholder="选择指令"
                   @change="changeMsg">
          <el-option
            v-for="item in cmdList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
        <el-divider content-position="left"><span style="color:#228AF5;">指令参数填入</span></el-divider>
        <!-- 拍照、录像、推流参数 -->
        <div v-if="showParameter1">
          <el-input style="margin: 10px 0px;" size="mini" placeholder="" v-model="form.http_url">
            <template slot="prepend">接口地址</template>
          </el-input>
          <div v-if="form.msg_type === 4">
            <el-radio-group size="small" v-model="form.action" @change="changeAction">
              <el-radio-button v-for="item in action"
                               :key="item.code"
                               :label="item.code">{{item.name}}
              </el-radio-button>
            </el-radio-group>
          </div>
          <!--          <div style="margin-top: 10px" v-if="form.action===1 || form.msg_type === 12">-->
          <!--            <el-radio-group size="small" v-model="form.codec">-->
          <!--              <el-radio-button v-for="item in codec"-->
          <!--                               :key="item.code"-->
          <!--                               :label="item.code">{{item.name}}-->
          <!--              </el-radio-button>-->
          <!--            </el-radio-group>-->
          <!--          </div>-->
          <!--          <div style="margin-top: 10px">-->
          <!--            <el-radio-group size="small" v-model="form.wdr" v-if="form.action===1 || form.msg_type === 12">-->
          <!--              <el-radio-button v-for="item in wdr"-->
          <!--                               :key="item.code"-->
          <!--                               :label="item.code">{{item.name}}-->
          <!--              </el-radio-button>-->
          <!--            </el-radio-group>-->
          <!--          </div>-->
          <el-input size="small" placeholder="" v-model="form.count" type="number" style="margin-top: 10px">
            <template slot="prepend">{{form.action===0?'抓拍数量':'录制时长'}}</template>
            <template slot="append" v-if="form.action===1 || form.msg_type === 12">秒</template>
          </el-input>
          <!--          <el-input size="small" v-model="form.channel" style="margin-top: 10px">-->
          <!--            <template slot="prepend">通道</template>-->
          <!--          </el-input>-->
          <!--          <el-input size="small" placeholder="默认是1080" v-model="form.width" style="margin-top: 10px">-->
          <!--            <template slot="prepend">分辨率宽</template>-->
          <!--          </el-input>-->
          <!--          <el-input size="small" placeholder="默认是720" v-model="form.height" style="margin-top: 10px">-->
          <!--            <template slot="prepend">分辨率高</template>-->
          <!--          </el-input>-->
        </div>
        <!-- 远程调焦距参数 -->
        <div v-if="form.msg_type === 20">
          <div style="margin-top: 10px">
            <el-radio-group size="mini" v-model="form.mode" @change="changeMode">
              <el-radio-button v-for="item in mode"
                               :key="item.code"
                               :label="item.code">{{item.name}}
              </el-radio-button>
            </el-radio-group>
          </div>
          <!--          聚焦模式-->
          <!--          <div style="margin-top: 10px" v-if="form.mode === 1">-->
          <!--            <el-radio-group size="mini" v-model="form.focus_mode">-->
          <!--              <el-radio-button v-for="item in focus_mode"-->
          <!--                               :key="item.code"-->
          <!--                               :label="item.code">{{item.name}}-->
          <!--              </el-radio-button>-->
          <!--            </el-radio-group>-->
          <!--          </div>-->
          <!--          <div style="margin-top: 10px" v-if="form.mode === 0">-->
          <!--            <el-radio-group size="mini" v-model="form.zoom_mode">-->
          <!--              <el-radio-button v-for="item in zoom_mode"-->
          <!--                               :key="item.code"-->
          <!--                               :label="item.code">{{item.name}}-->
          <!--              </el-radio-button>-->
          <!--            </el-radio-group>-->
          <!--          </div>-->
          <el-input style="margin-top: 10px" size="mini" v-if="form.mode === 0" placeholder="" v-model="form.zoom_rate"
                    type="number">
            <template slot="prepend">取值范围(zoom_rate)</template>
            <!--            <template slot="append">-->
            <!--              <el-tooltip class="item" effect="light" placement="bottom-end">-->
            <!--                <div slot="content">步长为6时,10倍变焦(-180,180)<br/>如果需要放大(拍远处),设置值为正数，否则为负数</div>-->
            <!--                <el-button>悬浮查看说明</el-button>-->
            <!--              </el-tooltip>-->
            <!--            </template>-->
          </el-input>
          <el-input size="mini" style="margin-top: 10px" placeholder="" v-model="form.focus_step"
                    type="number">
            <template slot="prepend">步长(focus_step)</template>
            <!--            <template slot="append">-->
            <!--              <el-tooltip class="item" effect="light" placement="bottom-end">-->
            <!--                <div slot="content">：默认8,0 – 10</div>-->
            <!--                <el-button>悬浮查看说明</el-button>-->
            <!--              </el-tooltip>-->
            <!--            </template>-->
          </el-input>
          <!--          <el-input v-if="form.mode === 0" size="mini" style="margin-top: 10px" placeholder=""-->
          <!--                    v-model="form.zoom_rate_curr"-->
          <!--                    type="number">-->
          <!--            <template slot="prepend">当前倍数(zoom_rate_curr)</template>-->
          <!--          </el-input>-->
        </div>
        <!-- 摄像机参数配置 -->
        <div v-if="form.msg_type === 28">
          <div style="margin-top: 10px">
            <el-radio-group size="mini" v-model="form.set_flag">
              <el-radio-button v-for="item in set_flag"
                               :key="item.code"
                               :disabled="item.code === 1"
                               :label="item.code">{{item.name}}
              </el-radio-button>
            </el-radio-group>
          </div>
          <div v-if="cameraInfo.msg_type">
            <ul>
              <li><span class="info_view" style="color: #ff4d51">4G信号强度：</span>{{(Number(cameraInfo.signal) + 113)/2}}
              </li>
              <li><span class="info_view" style="color: #ff4d51">电池电压：</span>{{cameraInfo.battery}}v</li>
              <li><span class="info_view">固件版本：</span>{{cameraInfo.firmware_version}}</li>
              <li><span class="info_view">设备ID：</span>{{cameraInfo.device_id}}</li>
              <li><span class="info_view">时间戳：</span>{{cameraInfo.timestamp | formatTimer}}</li>
              <li><span class="info_view">环境温度：</span>{{cameraInfo.temp_env}}</li>
              <li><span class="info_view">CPU温度：</span>{{cameraInfo.temp_cpu}}</li>
              <li><span class="info_view">照片像素宽度：</span>{{cameraInfo.width_tp}}</li>
              <li><span class="info_view">照片像素高度：</span>{{cameraInfo.height_tp}}</li>
              <li><span class="info_view">视频像素宽度：</span>{{cameraInfo.width_rv}}</li>
              <li><span class="info_view">视频像素高度：</span>{{cameraInfo.height_rv}}</li>
              <li><span class="info_view">自动拍照间隔：</span>{{cameraInfo.work_interval}}</li>
              <li><span class="info_view">开始工作时间：</span>{{cameraInfo.work_start}}</li>
              <li><span class="info_view">停止工作时间：</span>{{cameraInfo.work_stop}}</li>
              <li><span class="info_view">视频捕获时长：</span>{{cameraInfo.rv_duration}}</li>
            </ul>
          </div>
        </div>
        <!--  指令下发 -->
        <div v-if="form.msg_type === 52">
          <el-select value-key="id" v-model="at_cmds" style="width: 100%" allow-create filterable clearable
                     @change="changeCmdType"
                     placeholder="选择指令类型">
            <el-option
              v-for="item in cmdTypeList"
              :key="item.id"
              :label="item.cmd+item.info"
              :value="item">
            </el-option>
          </el-select>
          <el-select v-model="form.at_cmds[0].fields" style="width: 100%;margin-top: 10px" allow-create filterable
                     clearable
                     placeholder="选择指令参数">
            <el-option
              v-for="item in paraOption"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <div style="text-align: center">
          <el-button type="primary" style="background-color: green;color: white;width: 100%;margin-top: 10px"
                     @click="sendCmd()">下发指令
          </el-button>
        </div>
      </div>
    </el-header>
    <el-main class="middle">
      <el-tabs v-model="activeName">
        <el-tab-pane v-if="showTab" label="视频流获取" name="second">
          <div class="about">
            <el-button type="success" icon="el-icon-video-play" @click="playVideo">查看摄像头推流</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="抓拍照片" name="three">
          <el-radio-group size="mini" v-model="isTestPhoto" @change="clearPhotoList">
            <el-radio-button v-for="item in photoType"
                             :key="item.code"
                             :label="item.code">{{item.name}}
            </el-radio-button>
          </el-radio-group>
          <div style="margin-top: 10px">
            <el-input size="mini" placeholder="" v-model="page">
              <template slot="prepend">page</template>
            </el-input>
            <el-input style="margin: 10px 0px;" size="mini" placeholder="" v-model="pageSize">
              <template slot="prepend">pageSize</template>
            </el-input>
            <el-button type="primary" style="color: white;margin: 10px 0px;width: 100%" @click="getAllPhoto">获取照片数据
            </el-button>
          </div>
          <el-card
            shadow="always"
            class="base_img"
            :body-style="{ padding: '0px' }"
            v-for="(item, index) in imgList"
            :key="item.photoUrl">
            <el-image v-if="item.photoUrl.indexOf('.mp4') > -1" class="base_img-item" @click="play(item.photoUrl)"
                      :src="require('./playMp4.png')"></el-image>
            <el-image v-else class="base_img-item" @click="previewImg(index)" :src="constUrl+item.photoUrl"></el-image>
            <div v-if="isTestPhoto" class="base_img-time flex-between">
              <em style="display: inline-block;width: 210px;text-align: left">
                <p><em style="color: #1990FE;font-weight: 600">SN：</em>{{item.sn}}</p>
                <p><em style="color: #1990FE;font-weight: 600">抓拍时间：</em>{{item.bizTime |formatTimer}}</p>
                <p><em style="color: #1990FE;font-weight: 600">上传时间：</em>{{item.createTime |formatTimer}}</p>
                <p><span><em style="color: #1990FE;font-weight: 600">电压：</em>{{item.battery}}V</span>
                  <span><em style="color: #1990FE;font-weight: 600;margin-left: 30%">信号：</em>{{item.asignal}}</span></p>
                <el-button v-if="item.photoUrl.indexOf('.mp4') > -1" size="mini" type="text" class="btn_edit"
                           @click="play(item.photoUrl)">播放视频
                </el-button>
              </em>
            </div>
            <div v-else class="base_img-time flex-between">
              <em style="display: inline-block;width: 210px;text-align: left">
                <p><em style="color: #1990FE;font-weight: 600">SN：</em>{{item.cameraSn}}</p>
                <p><em style="color: #1990FE;font-weight: 600">抓拍时间：</em>{{item.bizTime |formatTimer}}</p>
                <p><em style="color: #1990FE;font-weight: 600">上传时间：</em>{{item.createTime |formatTimer}}</p>
                <p><em style="color: #1990FE;font-weight: 600">路线：</em>{{item.roadName}}</p>
                <p><em style="color: #1990FE;font-weight: 600">区间：</em>{{item.roadSectionName}}</p>
                <p><em style="color: #1990FE;font-weight: 600">布控点：</em> {{item.arrangementName}}</p>
                <el-button v-if="item.photoUrl.indexOf('.mp4') > -1" size="mini" type="text" class="btn_edit"
                           @click="play(item.photoUrl)">播放视频
                </el-button>
              </em>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="调试日志" name="first">
          <el-card class="box-card" shadow="always"
                   style="height: 100%;text-align: left;">
            <div slot="header" class="clearfix">
              <span style="color:#228AF5">数据交互窗口</span>
              <el-button type="primary" style="margin-left: 30px;" @click="msgObjList=[]">清空窗口</el-button>
            </div>
            <div id="data-list-content" style="height: 506px;word-break: break-all;overflow-y: auto">
              <template v-for="item in msgObjList">
                <p class="p-show" v-if="item.user=='client'" style="color: dodgerblue" :key="item.id">
                  {{item.date}}---发送指令：{{item.msg}}
                </p>
                <p class="p-show" v-if="item.user=='server' && item.level!='ERROR'" style="color: green" :key="item.id">
                  {{item.date}}---返回数据：{{item.msg}}
                </p>
                <p class="p-show" v-if="item.user=='server' && item.level=='ERROR'" style="color: red" :key="item.id">
                  {{item.date}}---返回数据：{{item.msg}}
                </p>
              </template>
            </div>
          </el-card>
          <!--          <el-card class="box-card" shadow="always"-->
          <!--                   style="height: 100%;width: 48%;text-align: left;margin-left:1%;display: inline-block">-->
          <!--            <div slot="header" class="clearfix" style="height:40px">-->
          <!--              <span style="color:#228AF5">数据处理窗口</span>-->
          <!--            </div>-->
          <!--            <el-button type="primary" @click="changeDataInfoToJson()" round>结构化数据</el-button>-->
          <!--            <el-input-->
          <!--              style="margin-top: 20px"-->
          <!--              type="textarea"-->
          <!--              :rows="20"-->
          <!--              placeholder="请输入数据内容"-->
          <!--              v-model="dataInfo">-->
          <!--            </el-input>-->
          <!--          </el-card>-->
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-dialog
      title="视频播放"
      v-if="playMp4"
      :visible.sync="playMp4"
      :close-on-click-modal="false"
      width="1080px">
      <video-player class="video-player vjs-custom-skin"
                    :playsinline="true"
                    :options="playerOptions">
      </video-player>
    </el-dialog>
    <picture-viewer ref="imageViewer"></picture-viewer>
  </el-container>
</template>

<script>
  import PictureViewer from '@/components/picture-viewer'
  import {Message} from 'element-ui'
  import {
    connectCamera,
    getCameraIdList,
    getFormalPhoto,
    getTestPhoto,
    sendCmd,
    unConnectCamera
  } from '@/services/model/camera'
  import constUrl from '@/services/env'
  import 'video.js/dist/video-js.css'
  import 'vue-video-player/src/custom-theme.css'
  import {videoPlayer} from 'vue-video-player'
  import 'videojs-flash'
  import Format from '@/utils/format'
  import 'videojs-swf/dist/video-js.swf';
  import Enums from '@/utils/enums'

  // videojs.options.flash.swf = SWF_URL // 设置flash路径，Video.js会在不支持html5的浏览中使用flash播放视频文件
  export default {
    mixins: [Enums],
    components: {PictureViewer, videoPlayer},
    data() {
      return {
        cameraId: '',
        page: 1,
        pageSize: 5,
        showTab: false,
        at_cmds: '',
        cmdTypeList: [
          {id: 0, cmd: 'campara', info: '分辨率', option: ['1,2592,1280', '2,1944,720', '1,1920,1280', '2,1080,720']},
          {id: 1, cmd: 'csclk', info: '休眠', option: ['0', '1', '1,60,1']},
          {id: 2, cmd: 'camisp', info: '照片压缩比(30~50)', option: ['11,50', "11,30"]},
          {id: 3, cmd: 'camisp', info: '拍照自动聚焦', option: ['14,0', '14,1']},
          {id: 4, cmd: 'camisp', info: '红外切换', option: ['15,0', '15,1']},
          {id: 5, cmd: 'camisp', info: '照片文字展示', option: ['13,B1B1BEA9BEC3B8D0BFC6BCBC', '14,2323']},
          {id: 6, cmd: 'campwr', info: '切换红外/下发后遮住镜头', option: ['1', '0']},
          {id: 7, cmd: 'factory', info: '上传日志', option: ['3']},
        ],
        cameraList: [
          "356802050245512",
          "356802050244242"
        ],
        playMp4: false,
        cameraInfo: {},//摄像机返回信息
        imgList: [],
        playerOptions: {
          playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
          autoplay: false, // 如果为true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 是否视频一结束就重新开始。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            type: "video/mp4", // 类型
            src: '' // url地址
          }],
          poster: '', // 封面地址
          notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true, // 当前时间和持续时间的分隔符
            durationDisplay: true, // 显示持续时间
            remainingTimeDisplay: false, // 是否显示剩余时间功能
            fullscreenToggle: true // 是否显示全屏按钮
          }
        },
        constUrl,
        activeName: 'three',
        //变倍或聚焦设置
        set_flag: [
          {name: "查询", code: 0},
          {name: "设置", code: 1},
        ],
        photoType: [
          {name: "测试照片", code: true},
          {name: "布控照片", code: false},
        ],
        //变倍或聚焦设置
        zoom_mode: [
          {name: "缩放后自动聚焦", code: 0},
          {name: "缩放后不聚焦", code: 1},
        ],
        //聚焦设置
        focus_mode: [
          {name: "自动模式", code: 0},
          {name: "粗调模式", code: 1},
          {name: "细调模式", code: 2},
        ],
        //变倍或聚焦设置
        mode: [
          {name: "聚焦模式", code: 1},
          {name: "缩放变倍", code: 0},
        ],
        wdr: [
          {name: "普通模式", code: 0},
          {name: "宽动态模式", code: 4},
        ],
        codec: [
          {name: "H.265", code: 0},
          {name: "H.264", code: 1},
        ],
        action: [
          {name: "抓拍图像", code: 0},
          {name: "录制视频", code: 1},
        ],
        cmd: '',
        uuid: '',
        connectStatus: false, // 连接状态
        isTestPhoto: true, // 测试照片
        selectCmd: '',
        dataInfo: '',
        msgObjList: [],
        paraOption: [],
        cameraSelectList: [],
        EnumCameraMsgTypeList: [],
        msgObj: {
          user: '', // 消息用户
          msg: '', // 消息内容
          date: '' // 时间
        },
        clientUser: 'client',
        serverUser: 'server',
        ws: null,
        form: {
          action: 0,
          http_url: 'http://hofuniot.cn/vt/upload.php',
          // width: 1920,
          // height: 1280,
          wdr: 0,
          codec: 0,
          mode: 0,
          at_cmds: [
            {
              cmd: 'campwr',
              fields: '0'
            }
          ],
        }
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer), 'yyyy-MM-dd hh:mm:ss')
      },
    },
    computed: {
      sn() {
        return this.$route.params.sn
      },
      showParameter1() {
        let type = [4, 12]
        return type.indexOf(this.form.msg_type) !== -1
      },
      cmdList() {
        let oftenList = [4, 20, 52, 28]
        let list = []
        this.EnumCameraMsgTypeList.map(x => {
          if (x.name.indexOf('下发') !== -1 && oftenList.indexOf(x.code) !== -1) {
            list.push(x)
          }
        })
        return list
      }
    },
    watch: {
      sn(val) {
        if (val) {
          this.cameraId = val
          this.$forceUpdate()
        }
      },
    },
    mounted() {
      this.uuid = this.getUUID();
      this.getCameraSelectList()
      this.queryDictList(['EnumCameraMsgType'], ['EnumCameraMsgTypeList'])
    },
    methods: {
      clearPhotoList() {
        this.imgList = []
      },
      async getCameraSelectList() {
        let {data} = await getCameraIdList();
        this.cameraSelectList = data || []
      },
      changeAction(val) {
        if (val === 0) {
          this.form.count = 1
        } else {
          this.form.count = 3
        }
      },
      changeMode() {
        this.form.focus_step = 6
      },
      changeCmdType(val) {
        if (val.option) {
          this.paraOption = val.option//参数选项
          this.form.at_cmds[0].cmd = val.cmd
          this.form.at_cmds[0].fields = this.paraOption[0]
        } else {
          //新增指令
          this.form.at_cmds[0].cmd = val
          this.form.at_cmds[0].fields = 1
        }

      },
      play(src) {
        this.playerOptions.sources[0].src = this.constUrl + src
        this.playMp4 = true
      },
      async getAllPhoto() {
        if (!this.cameraId) {
          this.$message(
            {
              type: 'error',
              showClose: true,
              message: '先选择摄像机'
            })
          return
        }
        let action = this.isTestPhoto ? getTestPhoto : getFormalPhoto
        let res = await action({page: this.page, pageSize: this.pageSize, queryString: this.cameraId})
        this.imgList = res.data.records
      },
      // 查看大图
      previewImg(index) {
        this.$refs.imageViewer.showViewer(this.imgList.map(x => this.constUrl + x.photoUrl), index)
      },
      playVideo(src) {
        this.$refs['playerObj'].playerOptions.sources[0].src = src
      },
      //选择指令，处理表单内容
      changeMsg(val) {
        if (val === 4) {
          this.form = {
            msg_type: val,
            action: 0,
            http_url: 'http://8.134.54.223:10000/record/camera-photo-record/v1/upload',
            // width: 1920,
            // height: 1280,
            wdr: 0,
            codec: 0,
            count: 1,
            channel: 2,
          }
          //  推流
        } else if (val === 12) {
          this.form = {
            msg_type: val,
            http_url: 'rtmp://hofuniot.cn:4199/live/356802050202455?user=test&sign=fb486b56434f22c70ac659ed1ac6cf06',
            mode: 0,
            wdr: 0,
            codec: 0,
          }
          //变倍聚焦
        } else if (val === 20) {
          this.form = {
            msg_type: val,
            mode: 1,
            zoom_mode: 1,
            focus_mode: 0,
            focus_step: 6,
            zoom_rate: -24,
            zoom_rate_curr: 0,
          }
          //配置信息
        } else if (val === 28) {
          this.form = {
            msg_type: val,
            set_flag: 0,
          }
          //at指令
        } else if (val === 52) {
          this.form = {
            msg_type: val,
            at_cmds: [
              {
                cmd: '',
                fields: '0'
              }
            ],
          }
        } else {
          this.form = {
            msg_type: val
          }
        }
      },
      scrollToBottom() {
        this.$nextTick(() => {
          // let div = document.getElementById('data-list-content')
          // div.scrollTop = div.scrollHeight
        })
      },
      alertMes(mes) {
        this.$message(
          {
            type: 'error',
            showClose: true,
            message: '请填入参数:' + mes
          })
      },
      changeDataInfoToJson: function () {
        var self = this
        var str = self.dataInfo
        try {
          str = str.replace(/ \+/g, '')
          str = str.replace(/[\r\n]/g, '')
          self.dataInfo = str
          let parseJSON = JSON.parse(self.dataInfo)
          self.dataInfo = JSON.stringify(parseJSON, null, 2)
        } catch (err) {
          this.$message(
            {
              type: 'error',
              showClose: true,
              message: '请传入正确的json数据！，也可通过：https://www.bejson.com/ 进行转换'
            })
        }
      }
      ,
      getUUID() {
        var s = []
        var hexDigits = '0123456789abcdef'
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
        }
        s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = '-'
        var uuid = s.join('')
        return uuid
      }
      ,
      logMsg(msg, user, level) {
        var resMsgObj = {}
        if (user === 'server' && msg.indexOf('{') === 0) {
          let info = JSON.parse(msg)
          if (info.msg_type === 27) {
            this.cameraInfo = info
          }
        }
        resMsgObj.msg = msg
        resMsgObj.level = level
        resMsgObj.user = user
        resMsgObj.date = this.getNowDate()
        resMsgObj.id = this.getUUID();
        this.msgObjList.push(resMsgObj)
        this.scrollToBottom()
      }
      ,
      //与设备建立或断开连接
      async connectEquip() {
        let form = {
          cameraId: this.cameraId,
          uuid: this.uuid,
        }
        if (!this.cameraId) {
          this.$message(
            {
              type: 'info',
              showClose: true,
              message: '请输入摄像机id！'
            })
          return
        }
        //连接状态，为断开连接
        if (this.connectStatus) {
          await unConnectCamera(form)
          this.connectStatus = false
          this.logMsg("和摄像机断开连接，摄像机id:" + this.cameraId, this.serverUser)
          this.ws.close()
          return
        }
        try {
          let res = await connectCamera(form)
          if (res.code === 200) {
            this.connectStatus = true
            this.logMsg("和摄像机成功建立连接，摄像机id:" + this.cameraId, this.serverUser)
            this.connectSocket()
          }
        } catch (e) {
          this.logMsg(e.message, this.serverUser, "ERROR")
        }
        this.cameraInfo = {}
      }
      ,
      //向设备发送指令
      async sendCmd() {
        if (!this.form.msg_type) {
          this.$message(
            {
              type: 'error',
              showClose: true,
              message: '请选择操作指令！'
            })
          return false
        }
        this.form.cameraId = this.cameraId
        this.form.uuid = this.uuid
        this.logMsg(this.form, this.clientUser)
        try {
          let res = await sendCmd(this.form)
          if (res.code === 200) {
            this.$message(
              {
                type: 'success',
                showClose: true,
                offset: 200,
                message: '指令下发成功!'
              })
            this.logMsg("下发的指令:" + res.data, this.serverUser)
          }
        } catch (e) {
          //设备已离线
          if (e.code === 101) {
            this.logMsg("指令下发失败：" + e.message, this.serverUser, "ERROR")
            this.connectStatus = false
          } else {
            this.logMsg("指令下发失败：" + e.message, this.serverUser, "ERROR")
          }
        }

      }
      ,
      connectSocket() {
        let uuid = this.uuid
        if ('WebSocket' in window) {
          // 打开一个 web socket
          this.ws = new WebSocket(`ws://8.134.64.118:9093/webSocket/camera/${uuid}`)
          this.ws.onopen = function () {
            console.log('websocket 连接上')
          }
          // 连接
          this.ws.onmessage = (evt) => {
            let mes = JSON.parse(evt.data)
            if (mes.uuid === uuid) {
              this.logMsg(mes.message + '', this.serverUser)
            }
          }
          this.ws.onclose = function (e) { // 监听关闭
            // this.ws.close()
            console.log('连接已关闭...')
          }
          this.ws.onerror = function (err) {
            // console.log(err)
          }
        } else {
          // 浏览器不支持 WebSocket
          Message({
            type: 'warning',
            message: '您的浏览器不支持 WebSocket!'
          })
        }
      }
      ,
      /**
       * 获得当前 年月日时分秒格式时间
       * @returns {string}
       */
      getNowDate: function () {
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth() + 1;
        let dd = new Date().getDate();
        let hh = new Date().getHours();
        let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
        return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
      }
      ,
    }
    ,

  }
</script>
<style scoped lang="less">
  .info-input {
    color: #228AF5;
    margin-left: 20px;
    font-weight: 600;
    font-size: 17px;
  }

  .info-parameter {
    color: #2dca7f;
    margin-left: 20px;
    font-weight: 600;
    font-size: 15px;
  }

  .input {
    width: 150px;
  }

  .el-select {
    width: 150px;
  }

  .heads {
    padding: 20px 0px;
    /*height: 400px !important;*/
    height: auto !important;
    margin: 0 auto;
    width: 90%;
  }

  .middle {
    height: 658px;
    width: 90%;
    border: dodgerblue solid 2px;
    margin: 20px auto;
  }

  .el-button--success {
    background-color: #67c23a;
  }

  .p-show {
    margin-top: 8px;
  }

  .el-main {
    overflow-y: auto;
  }

  .param-view {
    margin-top: 5px;
  }

  .el-divider--horizontal {
    margin: 15px 0;
  }

  .base_img {
    display: inline-block;
    margin-right: 20px;
    width: 100%;

    .el-button--text {
      color: black;
    }

    .base_img-item {
      /*width: 175px;*/
      height: 200px;
      cursor: pointer;
    }

    .base_img-name {
      padding: 10px 6px;
    }

    .base_img-time {
      font-size: 12px;
      padding: 0 6px 6px;
      color: #999;
    }
  }

  .info_view {
    display: inline-block;
    width: 100px;
    color: #1990FE;
    text-align: right;
  }
</style>
